/* 
 * Copyright [2018] [Alex/libo(liboware@gmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.codex.redis.model;

import java.util.Objects;
import java.util.Optional;
import java.util.Properties;

import lombok.Data;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/** 
 * @author LiBo/Alex
 * @see Redis Connection or session defination object
 * @since V1.0
 * @version V1.0 
 */
@Data
public final class JedisConnection {

    /**
     * ip
     */
    private String address;
    
    /**
     * socket port
     */
    private Integer port;
    
    /**
     * requredpass
     */
    private String password;
    
    /**
     * timeout
     */
    private Integer timeOut;
    
    /**
     * redis
     */
    private String clientName;
    
    /**
     * Jedis pool entity subject
     */
    private JedisPool jedisPool;
    
    /**
     * jedis client pool configuration
     */
    private JedisPoolConfig jedisPoolConfig;
    
    
    /**
     * build the base connection
     * @exception
     */
    private void buildJedis() {
        //是否为空
        if(Objects.isNull(jedisPool)) {
            if(Objects.isNull(jedisPoolConfig)) {
                 jedisPool = new JedisPool(new JedisPoolConfig(),address,port,timeOut,password,0,clientName);   
            }else {
                 jedisPool = new JedisPool(jedisPoolConfig,address,port,timeOut,password,0,clientName);   
            }
        }
    }
    
    /**
     * <b>openConnection</b>
     * @return
     * @exception
     */
    public Optional<Jedis> openSession() {
        buildJedis();
        if (jedisPool != null) {
            return Optional.of(jedisPool.getResource());
        }
        return null;
    }
}
